package com.yuexun.dhdoctor.module.mythings.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.base.BaseKJActivity;
import com.yuexun.dhdoctor.base.bean.model.HelpFileBean;
import com.yuexun.dhdoctor.base.bean.model.HelpFileData;
import com.yuexun.dhdoctor.base.bean.model.HelpFileEntity;
import com.yuexun.dhdoctor.base.bean.model.SubmitEntity;
import com.yuexun.dhdoctor.base.model.impl.HelpModel;
import com.yuexun.dhdoctor.base.presenter.impl.HelpPresent;
import com.yuexun.dhdoctor.base.ui.IHelpView;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.Contract.bean.People;
import com.yuexun.dhdoctor.module.commun.ui.Act_Choice_Member;
import com.yuexun.dhdoctor.module.email.adapter.MailFileAdapter;
import com.yuexun.dhdoctor.module.email.bean.MailFileBean;
import com.yuexun.dhdoctor.module.email.bean.MailFileDataBean;
import com.yuexun.dhdoctor.module.email.bean.UploadBean;
import com.yuexun.dhdoctor.module.email.model.impl.UploadModel;
import com.yuexun.dhdoctor.module.email.presenter.IUploadPresenter;
import com.yuexun.dhdoctor.module.email.presenter.impl.UploadPresenter;
import com.yuexun.dhdoctor.module.email.ui.view.IUploadView;
import com.yuexun.dhdoctor.module.mythings.bean.AnnualLeaveBean;
import com.yuexun.dhdoctor.module.mythings.bean.FlowMemberData;
import com.yuexun.dhdoctor.module.mythings.bean.TaskMainBean;
import com.yuexun.dhdoctor.module.mythings.bean.TypeData;
import com.yuexun.dhdoctor.module.mythings.model.impl.ThingModel;
import com.yuexun.dhdoctor.module.mythings.presenter.IThingAddPresenter;
import com.yuexun.dhdoctor.module.mythings.presenter.impl.TaskCloneDetailPresenter;
import com.yuexun.dhdoctor.module.mythings.presenter.impl.ThingAddPresenter;
import com.yuexun.dhdoctor.module.mythings.ui.view.ITaskCloneDetailView;
import com.yuexun.dhdoctor.module.mythings.ui.view.IThingAddView;
import com.yuexun.dhdoctor.util.CommonUtil;
import com.yuexun.dhdoctor.util.GetPathFromUri4kitkat;
import com.yuexun.dhdoctor.widget.ClickOneDialog;
import com.yuexun.dhdoctor.widget.FixedSwipeListView;
import com.yuexun.dhdoctor.widget.LoadingDialog;
import com.yuexun.dhdoctor.widget.ModelAddViewNew;
import com.yuexun.dhdoctor.widget.ToastDialog;
import com.yuexun.dhdoctor.widget.UploadDialog;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2018/9/11.
 */
public class Act_Things_Edit extends BaseKJActivity implements IThingAddView, IHelpView, IUploadView, ITaskCloneDetailView {

    @Bind(R.id.title_tv)
    TextView titleTv;
    @Bind(R.id.input_et_title_thing)
    EditText inputEtTitleThing;
    @Bind(R.id.et_person)
    TextView etPerson;
    @Bind(R.id.copy_me_et_person)
    TextView copyMeEtPerson;
    @Bind(R.id.flv_attachment)
    FixedSwipeListView flvAttachment;
    @Bind(R.id.input_et_content_thing)
    EditText inputEtContentThing;
    @Bind(R.id.thing_tv_type)
    TextView thingTvType;
    @Bind(R.id.help_attachment)
    FixedSwipeListView helpAttachment;
    @Bind(R.id.model_view)
    LinearLayout modelView;
    @Bind(R.id.select_txt)
    TextView selectTxt;
    @Bind(R.id.departorpeople)
    TextView departorpeople;
    @Bind(R.id.thing_iv_person_choose)
    ImageView personChoose;
    @Bind(R.id.select_depart)
    LinearLayout selectDepart;
    @Bind(R.id.animProgress)
    ProgressBar animProgress;
    @Bind(R.id.cope_me_ll)
    LinearLayout copeMeLl;

    UploadDialog uploadDialog;
    IUploadPresenter presenter_upload;
    IThingAddPresenter presenter;
    HelpPresent helpPresent;
    TaskCloneDetailPresenter clonePresenter;

    //上传的附件
    ArrayList<MailFileDataBean> mailFileDataBeans = new ArrayList<MailFileDataBean>();
    //帮助文件
    ArrayList<MailFileDataBean> helpFileDataBeans = new ArrayList<MailFileDataBean>();
    MailFileAdapter fileAdapter;
    MailFileAdapter mailFileAdapter;

    //输入的模板内容
    ArrayList<HelpFileData> dtlList = new ArrayList<>();
    //配置详情列表
    //选中的模板
    HelpFileEntity helpFileEntity;

    SubmitEntity entity;

    private LoadingDialog loadingDialog;

    //附件原路径
    private String img_path;

    TaskMainBean taskMainBean;
    //详情老数据
    TaskMainBean taskMainDtl;

    ArrayList<People> usersBeans_origin_copy = new ArrayList<>(); //抄送
    String copyPeople = "";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 20000:
                usersBeans_origin_copy = (ArrayList<People>) data.getExtras().getSerializable("persons");
                showSelectCopyPerson();
                break;
            case Activity.RESULT_OK:
                Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。
                img_path = GetPathFromUri4kitkat.getPath(this, uri);
                presenter_upload.uploadFile(img_path);
                break;
            default:
                break;
        }
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.act_thing_add);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        super.initData();
        titleTv.setText("克隆新建");
        taskMainDtl = (TaskMainBean) getIntent().getExtras().getSerializable("taskMainBean");
        mailFileDataBeans = (ArrayList<MailFileDataBean>) getIntent().getExtras().getSerializable("filelist");

        presenter = new ThingAddPresenter(new ThingModel(), this);
        helpPresent = new HelpPresent(new HelpModel(), this);
        presenter_upload = new UploadPresenter(new UploadModel(), this);
        clonePresenter = new TaskCloneDetailPresenter(new ThingModel(), this);

        uploadDialog = new UploadDialog(this);

        loadingDialog = new LoadingDialog(this);
        loadingDialog.setCanceledOnTouchOutside(false);

//        copeMeLl.setVisibility(View.VISIBLE);

        ApiGetCloneDetail();
    }

    //填充数据
    private void setDatas() {
        copyPeople = taskMainBean.getCarbonNames();
        String[] copyPeoples = copyPeople.split(";");
        String[] copyPeopleIds = taskMainBean.getCarbonIds().split(";");
        for (int i = 0; i < copyPeoples.length; i++) {
            People people = new People();
            people.setUserName(copyPeoples[i]);
            people.setUserId(copyPeopleIds[i]);
            usersBeans_origin_copy.add(people);
        }
        copyMeEtPerson.setText(taskMainBean.getCarbonNames());
        if (taskMainBean.getToType().equals("2")) {
            selectTxt.setText("部门处理");
        } else if (taskMainBean.getToType().equals("1")) {
            selectTxt.setText("个人处理");
        } else {
            selectTxt.setText("群组处理");
        }
        etPerson.setText(taskMainBean.getToName());
        thingTvType.setText(taskMainBean.getConfigName());
        inputEtTitleThing.setText(taskMainBean.getTitle());

        flvAttachment.setVisibility(View.VISIBLE);
        mailFileAdapter = new MailFileAdapter(this, mailFileDataBeans, true);
        flvAttachment.setAdapter(mailFileAdapter);

        personChoose.setImageResource(R.drawable.ic_task_add_unselect);
    }

    /**
     * 获取克隆详情
     */
    private void ApiGetCloneDetail() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("taskId", taskMainDtl.getTaskId());
        clonePresenter.getTaskCloneDatas(params);
    }

    /**
     * 获取模板详情
     */
    private void ApiGetTypeDetail() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("configId", taskMainBean.getConfigId() + "");
        presenter.getHelpFile(params);

        modelView.setVisibility(View.VISIBLE);
        if (!animProgress.isShown()) {
            animProgress.setVisibility(View.VISIBLE);
        }

//        Map<String, String> params2 = new HashMap<>();
//        params2.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
//        params2.put("configId", taskMainBean.getConfigId() + "");
//        params2.put("configType", "1");
//        params2.put("level", "0");
//        params2.put("fromMemberId", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.ACCOUNT_ID));
//        presenter.getFlowMember(params2);
    }

    /**
     * 获取类型的帮助文件
     *
     * @param fileUuid
     */
    private void initFileData(String fileUuid) {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("fileUuid", fileUuid);
        helpPresent.getFileData(params);
    }

    /**
     * 获取类型的帮助文件
     */
    private void helpFileShow() {
        if (helpFileEntity != null && helpFileEntity.getConfigUrls() != null &&
                !helpFileEntity.getConfigUrls().isEmpty()) {
            //帮助文件URL用;隔开
            String temp[] = helpFileEntity.getConfigUrls().split(";");
            for (int i = 0; i < temp.length; i++) {
                if (!temp[i].isEmpty()) {
                    initFileData(temp[i]);
                }
            }
            helpAttachment.setVisibility(View.VISIBLE);
        } else {
            ViewInject.toast("没有帮助文件");
            helpAttachment.setVisibility(View.GONE);
        }
    }

    @Override
    @OnClick({R.id.back, R.id.bar_text_submit, R.id.ll_extra_file, R.id.repair_help,
            R.id.copy_me_thing_iv_person_choose})
    public void onClick(View view) {
        if (CommonUtil.isFastClick()) {
            return;
        } else {
            switch (view.getId()) {
                case R.id.back:
                    finish();
                    break;
                case R.id.bar_text_submit:
                    if (inputEtTitleThing.getText().toString().isEmpty()) {
                        ViewInject.toast("主题不能为空");
                        break;
                    }
                    JudgeAnnualLeave();
                    break;
                case R.id.ll_extra_file:
                    select_file();
                    break;
                case R.id.repair_help:
                    if (thingTvType.getText().toString().isEmpty()) {
                        new ToastDialog(aty, "没有模板").show();
                    } else {
                        helpFileDataBeans.clear();
                        helpFileShow();
                    }
                    break;
                case R.id.copy_me_thing_iv_person_choose:
                    selectCopy();
                    break;
            }
        }
    }

    private void selectCopy() {
        Bundle bundle = new Bundle();
        Intent intent = new Intent(this, Act_Choice_Member.class);
        bundle.putSerializable("persons", usersBeans_origin_copy);
        bundle.putString("title", "新建事项");
        bundle.putString("type", "多选");
        bundle.putString("iscopy", "2");
        intent.putExtras(bundle);
        aty.startActivityForResult(intent, 1);
    }


    /**
     * 判断是否是年休假
     */
    private void JudgeAnnualLeave() {
            for (int i = 0; i < dtlList.size(); i++) {
                if (dtlList.get(i).getDtlName().equals("假期类别")) {
                    for (int j = 0; j < dtlList.get(i).getList().size(); j++) {
                        if (dtlList.get(i).getList().get(j).getDtlName().equals("年休假")) {
                            String dates = "";
                            for (HelpFileData fileData : dtlList) {
                                if (fileData.getDtlName().equals("请假时段")) {
                                    dates = fileData.getDtlValue();
                                }
                            }
                            getAnnualLeave(dates.split(" -- ")[0], dates.split(" -- ")[1]);
                            return;
                        }
                    }
                }
            }
            ApiForKjHttp();
    }

    /**
     * 获取年休假
     */
    private void getAnnualLeave(String startDate, String endDate) {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("startDate", startDate);
        params.put("endDate", endDate);
        params.put("configId", taskMainBean.getConfigId());
        presenter.getAnnualLeave(params);
    }

    /**
     * 新建事项
     */
    private void ApiForKjHttp() {

        String BaseUrl = AppConfig.WEB_SYSTEM + "createTask.json?";
        String partUrl = "";
        for (int i = 0; i < mailFileDataBeans.size(); i++) {
            partUrl = partUrl + "attachmentId=" + mailFileDataBeans.get(i).getFileUuid() + "&";
        }
        if (partUrl != null && partUrl.length() > 0) {
            partUrl = partUrl.substring(0, partUrl.length() - 1);
        }
        BaseUrl = BaseUrl + partUrl;

        KJHttp client = new KJHttp();
        HttpParams params = new HttpParams();
        String copyName = "", copyId = "";
        for (int i = 0; i < usersBeans_origin_copy.size(); i++) {
            if (copyName.length() == 0) {
                copyName = usersBeans_origin_copy.get(i).getUserName();
            } else {
                copyName = copyName + ";" + usersBeans_origin_copy.get(i).getUserName();
            }
            if (copyId.length() == 0) {
                copyId = usersBeans_origin_copy.get(i).getUserId();
            } else {
                copyId = copyId + ";" + usersBeans_origin_copy.get(i).getUserId();
            }
        }
        params.put("toId", taskMainBean.getToCount());
        params.put("toName", taskMainBean.getToName());
        params.put("toType", taskMainBean.getToType());
        params.put("carbonNames", copyName);
        params.put("carbonIds", copyId);

        params.put("content", inputEtContentThing.getText().toString());
        params.put("title", inputEtTitleThing.getText().toString());
        params.put("state", "1");
        params.put("configId", taskMainBean.getConfigId());
        params.put("configName", taskMainBean.getConfigName());

        params.put("sessionUuid", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        if (dtlList != null && !new ModelAddViewNew(aty, dtlList).isEmpty()) {
            loadingDialog.show();
            params.put("dtlJson", JSONArray.toJSONString(dtlList));
        } else {
            return;
        }

        client.post(BaseUrl, params, new HttpCallBack() {
            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                entity = JSON.parseObject(t, SubmitEntity.class);
                setUi();
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                ViewInject.toast(aty.getString(R.string.create_fail));
                loadingDialog.dismiss();
            }
        });
    }

    private void setUi() {
        if (entity.getStatus().equals("200")) {
            ViewInject.toast(aty.getString(R.string.create_success));
            loadingDialog.dismiss();
            finish();
        } else {
            ViewInject.toast(aty.getString(R.string.create_fail));
            loadingDialog.dismiss();
        }
    }

    /**
     * 显示选中的抄送人
     */
    private void showSelectCopyPerson() {
        copyPeople = "";
        for (People childDepartmentsBean : usersBeans_origin_copy) {
            if (copyPeople.isEmpty()) {
                copyPeople = childDepartmentsBean.getUserName();
            } else {
                copyPeople = copyPeople + ";" + childDepartmentsBean.getUserName();
            }
        }
        copyMeEtPerson.setText(copyPeople);
    }

    /**
     * 从设备读取文件
     */
    private void select_file() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 1);
    }

    @Override
    public void showTypeDatas(BaseEntity<TypeData> typeBean) {

    }

    @Override
    public void getHelpFile(HelpFileBean helpFileBean) {
        if (animProgress.isShown()) {
            animProgress.setVisibility(View.GONE);
        }
        if (helpFileBean.getStatus().equals("200")) {
            if (helpFileBean.getDatas().size() > 0) {
                helpFileEntity = helpFileBean.getDatas().get(0);
                if (taskMainDtl.getConfigName().equals(helpFileEntity.getConfigName())) {
                    dtlList.clear();
                    //类型显示模板
                    new ModelAddViewNew(aty, dtlList).showBackfill(helpFileEntity.getDtlList(), taskMainBean.getDtlList(), modelView);
                } else {
                    toastDialog();
                }
            } else {
                modelView.setVisibility(View.GONE);
            }

        } else {
            ViewInject.toast("该事项已经调整变化，无法克隆！请选择新建操作！");
        }
    }

    @Override
    public void getFlowMember(BaseEntity<FlowMemberData> s) {
        if (s.getStatus().equals("200")) {
            List<FlowMemberData> memberDatas = s.getDatas();
            if (memberDatas.size() > 0) {
                if (!taskMainBean.getToCount().equals(memberDatas.get(0).getMemberId() + "")) {
                    toastDialog();
                }
            }
        }
    }

    @Override
    public void getAnnualLeave(BaseEntity<AnnualLeaveBean> s) {
        if (s.getStatus().equals("200")) {
            ApiForKjHttp();
        } else {
            ViewInject.toast(s.getMessage());
        }
    }

    @Override
    public void getFileData(MailFileBean mailFileBean) {
        if (mailFileBean.getStatus().equals("200")) {
            helpFileDataBeans.add(mailFileBean.getDatas().get(0));
            if (mailFileAdapter == null) {
                mailFileAdapter = new MailFileAdapter(this, helpFileDataBeans, false);
                helpAttachment.setAdapter(mailFileAdapter);
            } else {
                mailFileAdapter.notifyDataSetChanged();
            }
        } else {
            Log.e("jx", "文件信息获取失败");
        }
    }

    @Override
    public void uploadDialogStatus(int status) {
        switch (status) {
            case AppConfig.SHOW_DIALOG:
                uploadDialog.setCanceledOnTouchOutside(false);
                uploadDialog.show();
                break;
            case AppConfig.DISMISS_DIALOG:
                uploadDialog.dismiss();
                break;
        }
    }

    @Override
    public void updateFile(UploadBean uploadBean) {
        if (mailFileDataBeans.size() == 0) {
            uploadBean.getData().get(0).setFileUrl(img_path);
            mailFileDataBeans.add(uploadBean.getData().get(0));
            fileAdapter = new MailFileAdapter(this, mailFileDataBeans, true);
            flvAttachment.setAdapter(fileAdapter);
        } else {
            uploadBean.getData().get(0).setFileUrl(img_path);
            mailFileDataBeans.add(uploadBean.getData().get(0));
            fileAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showTaskCloneDatas(BaseEntity<TaskMainBean> entity) {
        if (entity.getStatus().equals("200")) {
            taskMainBean = entity.getDatas().get(0);
            if (taskMainBean.getJudgeFlag() == 1) {
                setDatas();
                ApiGetTypeDetail();
            } else {
                toastDialog();
            }

        }
    }

    private void toastDialog() {
        final ClickOneDialog dialog = new ClickOneDialog(aty).builder().setCanceledOnTouchOutside(false).setContent("该事项已经调整变化，无法克隆！请选择新建操作！");
        dialog.setCallBack(new ClickOneDialog.ICallBack() {
            @Override
            public void sureCallback(String content) {
                dialog.dismiss();
                finish();
            }
        });
        dialog.show();
    }
}
